import * as Fiber from 'fiber';
const getWFParms4BugReport = (affairId) => {
  var _superviseManager = new superviseManager();

  var wfPrams = _superviseManager.getWFParms4BugReport(affairId);

  return wfPrams;
};
const getCtpAffair = (affairId) => {
  var _superviseManager = new superviseManager();

  var affair = _superviseManager.getCtpAffairbyAffairId(affairId);

  return affair;
};

const isTriggerReceiveFlow = (summaryId) => {
  if (window._hasPlugin('edoc')) {
    return callBackendMethod('workflowManageManager', 'isTriggerReceiveFlow', summaryId);
  }
  return false;
};

function repealWorkflow(row, callback, _data, dialog, { managerType, dataType } = {}) {
  var data = row;
  var params = {};
  if (dataType === 'workflowBug') {
    if (!data.affairId) {
      $.alert($.i18n('workflow.supervise.bugreport.canot.operation.js'));
      return;
    }

    var _affairId = data.affairId;

    var affair = getCtpAffair(_affairId);

    params = {
      endFlag: affair.finish == '0' ? '1' : '0',
      caseId: affair.caseId,
      processId: affair.processId,
      summaryId: affair.objectId,
      appName: affair.appEnumStr,
      isTemplate: affair.templeteId ? true : false
    };
  } else {
    params = { ...data };
  }

  repealWorkflowFn(params, dialog, callback);
}

function stopWorkflow(row, callback, _data, dialog, { managerType, dataType } = {}) {
  var data = row;
  var params = {};
  if (dataType === 'workflowBug') {
    if (!data.affairId) {
      $.alert($.i18n('workflow.supervise.bugreport.canot.operation.js'));
      return;
    }

    var _affairId = data.affairId;
    var affair = getCtpAffair(_affairId);

    params = {
      endFlag: affair.finish == '0' ? '1' : '0',
      caseId: affair.caseId,
      processId: affair.processId,
      summaryId: affair.objectId,
      appName: affair.appEnumStr,
      isTemplate: affair.templeteId ? true : false
    };
  } else {
    params = { ...data };
  }

  var sucessCallBackFn = function () {
    dealProblem(null, row, callback);
  };
  stopWorkflowFn(params, dialog, sucessCallBackFn);
}
function dealProblem(_dealType, row, callback) {
  var _summaryId;
  var dealType = 0;
  if (!row) {
    return;
  }

  _summaryId = row.summaryId;

  if (_dealType && dealType == 'unlock') {
    dealType = _dealType;
  } else {
    dealType = '';
  }
  var options = {
    summaryId: _summaryId,
    dealType: dealType
  };
  var _workflowBugReportManager = new workflowBugReportManager();
  _workflowBugReportManager.setAlreadyDeal(options, {
    success: function () {
      callback && callback();
    },
    error: function (request, settings, e) {
      $.alert(e);
    }
  });
}

function editFlowChartFn(selectRow, row, buttonParams = {}, { managerType, dataType } = {}) {
  var targetWin = window.parent;
  var caseId = selectRow.caseId;
  var valueWin = window.parent;
  var processId = selectRow.processId;
  var defaultNodeName = selectRow.defaultNodeName;
  var defaultNodeLable = selectRow.defaultNodeLable;
  var SPK = selectRow.spk;
  var NPS = selectRow.nps;

  var _repealWorkflow = repealWorkflow;
  var _stopWorkflow = stopWorkflow;
  var processState = wfAjax.getProcessState(processId);
  if (processState == 1) {
    $.alert($.i18n('collaboration.worklfow.state.error.msg.js')); //流程已结束或者终止，无法继续进行操作！
    return;
  }
  var isTemplate = selectRow.isTemplate;
  if (typeof isTemplate == 'undefined') {
    isTemplate = selectRow.isFromTemplete;
  }
  var appName = selectRow.appName;
  if (typeof appName == 'undefined') {
    appName = selectRow.appEnumStr;
  }
  var accountId = selectRow.flowPermAccountId;
  if (!selectRow.flowPermAccountId) {
    accountId = selectRow.accountId;
  }

  var _formAppId = selectRow.formAppId;
  var _masterId = selectRow.formRecordId;
  if (!SPK || SPK == 'undefined') {
    SPK = 'freeFlow';
  }
  if (!NPS || NPS == 'undefined') {
    NPS = 'default';
  }

  let buttons = [
    {
      id: 'saveDBOK',
      callBackFn: () => {
        let callback = buttonParams.saveDBOK.callback;
        callback && callback();
      }
    },
    {
      id: 'repeal',
      callBackFn: (data, dialog) => {
        let callback = buttonParams.repeal.callback;
        _repealWorkflow(row, callback, data, dialog, { managerType, dataType });
      }
    },
    {
      id: 'stop',
      callBackFn: (data, dialog) => {
        let callback = buttonParams.stop.callback;
        _stopWorkflow(row, callback, data, dialog, { managerType, dataType });
      }
    },
    {
      id: 'close',
      callBackFn: () => {
        let callback = buttonParams.close.callback;
        callback && callback();
      }
    }
  ];

  buttons = buttons.filter((btn) => {
    if (buttonParams) {
      return buttonParams[btn.id]?.show;
    } else {
      return false;
    }
  });

  var options = {
    targetWin: getCtpTop(),
    valueWin: valueWin,
    caseId: caseId,
    processId: processId,
    isTemplate: isTemplate,
    showHastenButton: false,
    appName: appName,
    scene: 5,
    currentUserId: _currentUser.id,
    flowPermAccountId: accountId,
    defaultPolicyId: defaultNodeName,
    defaultPolicyName: defaultNodeLable,
    SPK: SPK,
    NPS: NPS,
    isSkipNode: selectRow.isSkipNode,
    formAppId: _formAppId,
    masterId: _masterId,
    title: $.i18n('common.design.workflow.label'),
    isAdminMangerModel: true,
    canExePrediction: selectRow.bodyType === '20' && window._hasPlugin('workflowAdvanced'),
    buttons: buttons,
    callBackFn: selectRow.callBackFn
  };
  var summaryId = selectRow.summaryId;
  if (typeof summaryId != 'undefined') {
    var secretLevelValue = callBackendMethod('secretAjaxManager', 'getFileSecretLevel', summaryId);
    options.accessFileSecretLevel = secretLevelValue;
  }
  showDiagram(options);
}

function repealWorkflowFn(data, dialog, callback) {
  var caseId = data.caseId;
  var processId = data.processId;
  var summaryId = data.summaryId;
  var isTemplate = data.isTemplate;
  var idMap = {
    processId: processId,
    caseId: caseId,
    summaryId: summaryId
  };
  const sendDevelop = $.ctp.trigger('beforeDealCancel', idMap);
  if (!sendDevelop) {
    return;
  }
  if (typeof isTemplate == 'undefined') {
    isTemplate = data.isFromTemplete;
  }
  var appName = data.appName;
  if (typeof appName == 'undefined') {
    appName = data.appEnumStr;
  }
  if (
    appName == 'edoc' &&
    (processId == null || processId == '0' || processId == '') &&
    data.quickSend
  ) {
    $.alert($.i18n('relive.govdoc.old.msg.repeal'));
    return;
  }
  if (isTriggerReceiveFlow(summaryId)) {
    $.alert('触发产生的收文，暂不支持撤销。');
    return;
  }

  var isAdmin = _currentUser.isAdmin;
  //只有协同，表单 在单位管理员和表单管理员处才能撤销已结束的流程
  var canRealProcessFinish = isAdmin /* && appName == "collaboration"*/ ? 'true' : 'false';

  if (appName == 'edoc' && 4 == data.appEnum) {
    var ajaxManager = new govdocAManager();
    var params = new Object();
    params['summaryId'] = summaryId; //校验是否流程结束、是否审核、是否核定，涉及到的子流程调用工作流接口校验
    var canDealCancel = ajaxManager.checkIsCanRepeal(params);
    if (canDealCancel.msg != null) {
      $.alert(canDealCancel.msg);
      return;
    }
  }
  //调用工作流接口校验是否能够撤销流程
  var result = onBeforeWorkflowOperationValidate(
    processId,
    '',
    'start',
    '',
    '',
    appName || 'collaboration',
    'repeal',
    canRealProcessFinish
  );

  var msg = '';
  if (result && !result.pass) {
    msg = result.msg;
  }

  var _procesBar = $.progressBar();

  if (msg) {
    _procesBar.close();

    $.alert(msg);
    //核定的时候撤销流程解锁点取消  要解开流程锁
    releaseWorkflowByAction(processId, _wfcurrentUserId, 12);
    return;
  }

  var params = new Object();
  params['summaryId'] = summaryId;
  params['canCancleFinishProcess'] = canRealProcessFinish;
  params['appName'] = appName;

  // 校验是否可以撤销
  callBackendMethod('workflowManageManager', 'checkIsCanRepeal', params, {
    success: function (canDealCancel) {
      _procesBar.close();
      if (canDealCancel && canDealCancel.msg) {
        if (canDealCancel.isConfirm == 'true' && isAdmin) {
          if (!confirm($.i18n('collaboration.confirmRepeal.workflowIsRollback'))) {
            //核定的时候撤销流程解锁点取消  要解开流程锁
            releaseWorkflowByAction(processId, _wfcurrentUserId, 12);
            _procesBar.close();
            return;
          }
        } else {
          $.alert(canDealCancel.msg);
          //核定的时候撤销流程解锁点取消  要解开流程锁
          releaseWorkflowByAction(processId, _wfcurrentUserId, 12);
          _procesBar.close();
          return;
        }
      }

      //撤销流程
      var repealdialog = $.dialog({
        url: _ctxPath + '/workflowmanage/workflowmanage.do?method=showRepealCommentDialog',
        width: 450,
        height: 240,
        title: $.i18n('common.toolbar.repeal.label'), //撤销流程
        targetWindow: getCtpTop(),
        buttons: [
          {
            id: 'okBtn',
            text: $.i18n('common.button.ok.label'), //确定
            handler: function () {
              var returnValue = repealdialog.getReturnValue();
              if (returnValue) {
                repealdialog.disabledBtn('okBtn');
                var wmManager = new workflowManageManager();
                var tempMap = new Object();
                tempMap['page'] = 'workflowManager';
                tempMap['repealComment'] = returnValue[0];
                tempMap['summaryId'] = summaryId;
                tempMap['appName'] = appName;
                tempMap['canCancleFinishProcess'] = canRealProcessFinish;
                wmManager.transRepal(tempMap, {
                  success: function (msg) {
                    if (msg == null || msg == '') {
                      callback && callback();
                    } else {
                      $.alert(msg);
                    }
                    repealdialog.close();
                    if (dialog) {
                      dialog.close();
                    }
                  }
                });
              }
            }
          },
          {
            text: $.i18n('common.button.cancel.label'), //取消
            handler: function () {
              releaseWorkflowByAction(processId, _wfcurrentUserId, 12);
              repealdialog.close();
            }
          }
        ],
        closeParam: {
          show: true,
          handler: function () {
            releaseWorkflowByAction(processId, _wfcurrentUserId, 12);
          }
        }
      });
    },
    error: function (msg) {
      _procesBar.close();
      $.alert(msg);
    }
  });
}

function stopWorkflowFn(data, dialog, sucessCallBackFn, bckFun) {
  if (data.endFlag == '0') {
    $.alert($.i18n('collaboration.bpm.supervise.wf.isFinish'));
    return;
  }
  var caseId = data.caseId;
  var processId = data.processId;
  var summaryId = data.summaryId;
  var idMap = {
    processId: processId,
    caseId: caseId,
    summaryId: summaryId
  };
  console.log('$.ctp.trigger', 'beforeDealstepstop', idMap);
  const sendDevelop = $.ctp.trigger('beforeDealstepstop', idMap);
  if (!sendDevelop) {
    return;
  }
  var obj = canStopFlow(caseId);

  var isTemplate = data.isTemplate;
  if (typeof isTemplate == 'undefined') {
    isTemplate = data.isFromTemplete;
  }
  var appName = data.appName;
  if (typeof appName == 'undefined') {
    appName = data.appEnumStr;
  }

  //不能回退
  if (obj[0] === 'false') {
    $.alert(obj[1]);
    return;
  }
  var lockWorkflowRe = lockWorkflow(processId, _wfcurrentUserId, 11);
  if (lockWorkflowRe[0] == 'false') {
    $.alert(lockWorkflowRe[1]);
    return;
  }
  $.messageBox({
    type: 1,
    imgType: 4,
    title: $.i18n('common.system.hint.label'),
    msg: $.i18n('collaboration.confirmStepStopItem'), //'确认要终止流程?该操作不能恢复!',
    ok_fn: function () {
      var wmManager = new workflowManageManager();
      var tempMap = new Object();
      tempMap['summaryId'] = summaryId;
      tempMap['appName'] = appName;
      wmManager.transStepStop(tempMap, {
        success: function (msg) {
          releaseWorkflowByAction(processId, _wfcurrentUserId, 11);
          bckFun && bckFun();
          if (msg == null || msg == '') {
            if (sucessCallBackFn) {
              sucessCallBackFn();
            }
          } else {
            $.alert(msg);
          }
        }
      });
      if (dialog) {
        dialog.close();
      }
    },
    cancel_fn: function () {
      releaseWorkflowByAction(processId, _wfcurrentUserId, 11);
      bckFun && bckFun();
    }
  });
}

function getAffair(affairId) {
  var _affairManager = new affairManager();
  var affObj = _affairManager.get(affairId);
  return affObj;
}

function getCurrentTime() {
  var date = new Date();
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var hour = date.getHours();
  var time = year + '-' + month + '-' + day + ' ' + hour + ':' + '00';
  return time;
}

function getCurrentDate() {
  var date = new Date();
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var date = year + '-' + month + '-' + day;
  return date;
}

function addUrlPath(urlStr, templeteIds) {
  var _url = urlStr;
  var _loca = window.location.href;

  if (_loca.indexOf('srcFrom=bizconfig') != -1) {
    //控制面包削
    _url += '&srcFrom=bizconfig&condition=templeteIds&templeteIds=' + templeteIds;
  }

  return _url;
}
function getEdocType(type) {
  var edocType = 'default';

  if (type == '401') {
    edocType = 'govdocSend';
  } else if (type == '402') {
    edocType = 'govdocRec';
  } else if (type == '404') {
    edocType = 'govdocSign';
  }

  return edocType;
}

function getDataIds(data) {
  var processIdAndCaseIdAndFormAppIdAndMasterId = '';

  for (var i = 0; i < data.length; i++) {
    if (processIdAndCaseIdAndFormAppIdAndMasterId == '') {
      processIdAndCaseIdAndFormAppIdAndMasterId =
        data[i].processId +
        '_' +
        data[i].caseId +
        '_' +
        data[i].formAppId +
        '_' +
        data[i].formRecordId;
    } else {
      processIdAndCaseIdAndFormAppIdAndMasterId +=
        ',' +
        data[i].processId +
        '_' +
        data[i].caseId +
        '_' +
        data[i].formAppId +
        '_' +
        data[i].formRecordId;
    }
  }

  return processIdAndCaseIdAndFormAppIdAndMasterId;
}

function getSenderAffairId(summaryId) {
  var _affairId = 0;

  var _superviseManager = new superviseManager();

  var objSum = _superviseManager.getSenderAffair(summaryId);

  if (null != objSum && objSum.affairId != null) {
    _affairId = objSum.affairId;
  }

  return _affairId;
}
function checkSameTemplate(data) {
  var selectRows = data;
  if (selectRows.length === 0) {
    $.alert($.i18n('supervise.please.select.operation.data')); //请选择要操作的数据！
    return false;
  }
  if (selectRows.length === 1 && !selectRows[0].templeteId) {
    $.alert($.i18n('workflow.manager.supervise.modify.mag8.js')); //只能修改模板数据
    return false;
  }
  for (var i = 0; i < selectRows.length - 1; i++) {
    if (!selectRows[i].templeteId) {
      $.alert($.i18n('workflow.manager.supervise.modify.mag8.js')); //选择的数据不是同一个模板产生的数据！
      return false;
    }
    if (selectRows[i].templeteId != selectRows[i + 1].templeteId) {
      $.alert($.i18n('workflow.manager.supervise.modify.mag9.js')); //选择的数据不是同一个模板产生的数据！
      return false;
    }
  }
  return true;
}

function batchEditFlowChartFn(
  selectRow,
  processIdAndCaseIdAndFormAppIdAndMasterId,
  obj,
  total,
  _callback,
  { managerType, dataType, searchParams } = {}
) {
  var targetWin = window.parent;
  var caseId = selectRow.caseId;
  var valueWin = window.parent;
  var defaultNodeName = selectRow.defaultNodeName;
  var defaultNodeLable = selectRow.defaultNodeLable;
  var SPK = selectRow.spk;
  var NPS = selectRow.nps;
  var processState = wfAjax.getProcessState(obj.workflowId);

  if (processState == 1) {
    $.alert($.i18n('collaboration.worklfow.state.error.msg.js')); //流程已结束或者终止，无法继续进行操作！

    return;
  }

  var isTemplate = selectRow.isTemplate;

  if (typeof isTemplate == 'undefined') {
    isTemplate = selectRow.isFromTemplete;
  }

  var appName = selectRow.appName;

  if (typeof appName == 'undefined') {
    appName = selectRow.appEnumStr;
  }

  var accountId = selectRow.accountId;

  if (selectRow.flowPermAccountId) {
    accountId = selectRow.flowPermAccountId;
  }

  var _formAppId = selectRow.formAppId;
  var _masterId = selectRow.formRecordId;

  if (!SPK || SPK == 'undefined') {
    SPK = 'freeFlow';
  }

  if (!NPS || NPS == 'undefined') {
    NPS = 'default';
  }

  var options = {
    targetWin: getCtpTop(),
    valueWin: valueWin,
    caseId: caseId,
    processId: obj.workflowId,
    isTemplate: isTemplate,
    showHastenButton: false,
    appName: appName,
    scene: 5,
    currentUserId: _wfcurrentUserId,
    flowPermAccountId: accountId,
    defaultPolicyId: defaultNodeName,
    defaultPolicyName: defaultNodeLable,
    SPK: SPK,
    NPS: NPS,
    isSkipNode: selectRow.isSkipNode,
    formAppId: _formAppId,
    masterId: _masterId,
    title: $.i18n('common.design.workflow.label'),
    isAdminMangerModel: true,
    isSuperviseBatch: true,
    processIdAndCaseIdAndFormAppIdAndMasterId: processIdAndCaseIdAndFormAppIdAndMasterId,
    canExePrediction: selectRow.bodyType === '20' && $.ctx.hasPlugin('workflowAdvanced'),
    templateSubject: obj.subject,
    modifyTotal: total,
    buttons: [
      {
        id: 'saveDBOK',
        callBackFn: (ret) => {
          if (ret && ret.modifyTotal) {
            //批量修改所有
            var o = searchParams;
            o.superviseBatchModify = 'true';

            if (ret.modifyTotal <= 200) {
              //同步处理
              o.pageSize = '200';
              var re,
                ids = '';

              if (managerType == 'mySupervise') {
                o.managerType = 'mySupervise';

                var _superviseManager = new superviseManager();

                re = _superviseManager.getAllSuperviseList4Col({}, JSON.stringify(o));
                ids = getDataIds(re.data);
              } else {
                var wmManager = new workflowManageManager();
                re = wmManager.getSuperviseAllTemplateData(JSON.stringify(o));
                ids = getDataIds(re);
              }

              ret.processIdAndCaseIdAndFormAppIdAndMasterId = ids;
              var result = wfAjax.saveSuperviseBatchModifyWorkflowData(ret);

              if (result) {
                $.alert(
                  $.i18n(
                    'collaboration.common.workflow.supervise.batch.modify.title',
                    result.updateCount,
                    result.allCount - result.updateCount
                  )
                );
                _callback && _callback();
              }
            } else {
              //大于200条数据异步处理
              var confirm = $.confirm({
                msg: $.i18n('workflow.manager.supervise.modify.msg1.js'),
                ok_fn: function ok_fn() {
                  o.modifyTotal = ret.modifyTotal;
                  ret.isModifyAll = 'true';
                  var param = {
                    modifyData: ret,
                    modifyTotal: ret.modifyTotal,
                    isModifyAll: 'true',
                    serchData: o
                  };
                  callBackendMethod(
                    'superviseManager',
                    'saveSuperviseBatchModifyWorkflowData',
                    param,
                    {
                      success: function (result) {
                        _callback && _callback();
                      }
                    }
                  );
                },
                cancel_fn: function cancel_fn() { }
              });
            }
          } else if (ret && ret.allCount) {
            $.alert(
              $.i18n(
                'collaboration.common.workflow.supervise.batch.modify.title',
                ret.updateCount,
                ret.allCount - ret.updateCount
              )
            );
            _callback && _callback();
          }
        }
      },
      {
        id: 'close'
      }
    ],
    callBackFn: selectRow.callBackFn
  };
  showDiagram(options);
}

function __batchEdit(
  obj,
  data,
  modifyAll,
  { managerType, dataType, allData, searchParams } = {},
  _callback
) {
  var processIdAndCaseIdAndFormAppIdAndMasterId = '';
  var selectRow = {};
  var isForm = false;

  if (!modifyAll) {
    for (var i = 0; i < data.length; i++) {
      if (processIdAndCaseIdAndFormAppIdAndMasterId == '') {
        processIdAndCaseIdAndFormAppIdAndMasterId =
          data[i].processId +
          '_' +
          data[i].caseId +
          '_' +
          data[i].formAppId +
          '_' +
          data[i].formRecordId;
      } else {
        processIdAndCaseIdAndFormAppIdAndMasterId +=
          ',' +
          data[i].processId +
          '_' +
          data[i].caseId +
          '_' +
          data[i].formAppId +
          '_' +
          data[i].formRecordId;
      }
    }

    selectRow = data[0];
    var isCollaboration =
      selectRow.appEnumStr == 'collaboration' || selectRow.appName == 'collaboration';

    if (managerType == 'mySupervise' && dataType == 'all') {
      isForm = selectRow.formAppId && selectRow.bodyType == '20';
    } else {
      isForm = selectRow.formAppId && selectRow.templeteId;
    }

    if (isCollaboration && isForm) {
      selectRow.spk = 'collaboration_template_form';
      selectRow.nps = 'form';
    }
  } else {
    //批量修改所有
    if (obj.moduleType == '1' && (obj.type == 'template' || obj.type == 'appWorkflow')) {
      if (obj.formAppId) {
        selectRow.spk = 'collaboration_template_form';
        selectRow.nps = 'form';
        selectRow.appName = 'collaboration';
      } else {
        selectRow.spk = 'collaboration_template';
        selectRow.nps = 'default';
        selectRow.appName = 'collaboration';
      }
    } else {
      var rows = allData;
      var row = rows[0]; // 获取表格中得第一个数据来获取默认节点权限

      selectRow.defaultNodeName = row.defaultNodeName;
      selectRow.defaultNodeLable = row.defaultNodeLable;

      if (
        (obj.moduleType == '401' ||
          obj.moduleType == '402' ||
          obj.moduleType == '404' ||
          obj.moduleType == '4') &&
        (obj.type == 'template' || obj.type == 'appWorkflow') &&
        obj.formAppId
      ) {
        selectRow.appName = 'edoc';
      }

      selectRow.spk = 'freeFlow';
      selectRow.nps = getEdocType(obj.moduleType);
    }
  }

  selectRow.formAppId = obj.formAppId;
  selectRow.flowPermAccountId = obj.flowPermAccountId || obj.orgAccountId;

  batchEditFlowChartFn(selectRow, processIdAndCaseIdAndFormAppIdAndMasterId, obj, data, _callback, {
    managerType,
    dataType,
    searchParams
  });
}
let secretLevelEnable = false;
const getSecretLevelEnable = () => {
  if (getSecretLevelEnable.value) {
    return getSecretLevelEnable.value;
  }
  let value = window.callBackendMethod('secretAjaxManager', 'secretLevelEnable');
  getSecretLevelEnable.value = value;
  return value;
};

import { formatRequestDataToJSON } from '@/utils/api';
import { getDefaultValueSearchCondition } from '@/utils';

export default {
  data() {
    return {
      showType: 0, // 数据呈现颗粒度 0：无， 1：节点，2：泳道
      specialSearchConditionList: [],
      specialSearchSelectedValue: '',
      specialSearchConditionParams: null,
      searchConditions: []
    };
  },
  mounted() { },
  computed: {
    isShowSpecialSearchCondition() {
      if (
        this.showType != 0 &&
        this.specialSearchConditionList &&
        this.specialSearchConditionList.length > 0 &&
        (this.dataType && this.dataType == 'pending' || this.currentChooseVal == 'all' || this.currentChooseVal == '')
      ) {
        return true;
      } else {
        return false;
      }
    }
  },
  methods: {
    //修改日志
    editWorkFlowLog() {
      $.dialog({
        url: window._ctxPath + '/detaillog/detaillog.do?method=showSuperviseBatchModifyDetailLog',
        width: 1040,
        height: 590,
        title: $.i18n('collaboration.sendGrid.findAllLog'), //查看明细日志
        targetWindow: window.getCtpTop()
      });
    },
    //催办
    urgeDealHandler(rowData, _callback) {
      var selectRow = rowData;
      if (selectRow.endFlag == '0' || selectRow.finished) {
        Fiber.message.warning($.i18n('collaboration.bpm.supervise.wf.isFinish'));
        return;
      }
      var _affairId = selectRow.affairId;
      var _url = window._ctxPath + '/hasten.do?method=openHasten&summaryId=' + selectRow.summaryId;
      var _this = this;
      var canHandle = true;
      this[_affairId] = window.getCtpTop().$.dialog({
        id: 'hasten' + _affairId,
        width: 300,
        height: 420,
        url: _url,
        shadow: false,
        checkMax: false,
        // targetWindow: window.getCtpTop(),
        transParams: {
          pwindow: window
        },
        buttons: [
          {
            text: '确定',
            isEmphasize: true,
            handler: function () {
              if (!canHandle) {
                return;
              }
              canHandle = false;
              var _getReturnValue = JSON.parse(_this[_affairId].getReturnValue());
              var returnValue = _getReturnValue.returnValue;
              if (_getReturnValue.success) {
                window.callBackendMethod('hastenManager', 'hasten', returnValue, {
                  success: function (_result) {
                    Fiber.message.success(_result);
                    _this[_affairId].close();
                    _callback && _callback();
                    canHandle = true;
                  },
                  error: function (error) {
                    console.error(error);
                    canHandle = true;
                  }
                });
              }
            }
          },
          {
            text: '取消',
            handler: function () {
              _this[_affairId].close();
            }
          }
        ]
      });
    },
    //删除
    deleteSupervise(chooseData, _callback) {
      var rows = chooseData;
      var len = rows.length;
      var str = '';
      for (var i = 0; i < len; i++) {
        str += rows[i].id;
        str += ',';
      }
      if (len === 0) {
        $.alert($.i18n('collaboration.workflow.label.pleaseChoose'));
        return false;
      }
      str = str.substring(0, str.length - 1);
      $.confirm({
        msg: $.i18n('collaboration.common.supervise.sureDeleteSupervise'), //确定要删除督办记录?'
        ok_fn: function () {
          const args = `managerMethod=deleteSupervisedAjax&arguments=${JSON.stringify(str)}`;
          const url = `${window._ctxPath}/ajax.do?method=ajaxAction&managerName=superviseManager`;
          window.axios
            .post(url, args, {
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
              }
            })
            .then((data, err) => {
              if (data.status == 200) {
                for (var i = 0; i < rows.length; i++) {
                  try {
                    let affairId = getSenderAffairId(rows[i].summaryId);
                    window.closeOpenMultyWindow(affairId);
                  } catch (e) {
                    console.log(e);
                  }
                }

                _callback && _callback();
              }
            });
        }
      });
    },

    // 编辑流程
    editFlowChart(row, buttonParams, { managerType, dataType } = {}) {
      var data = row;
      var params = {};
      if (dataType === 'workflowBug') {
        // 流程异常特殊处理
        if (!data.affairId) {
          $.alert($.i18n('workflow.supervise.bugreport.canot.operation.js'));
          return;
        }

        var wfParams = getWFParms4BugReport(data.affairId);

        params = {
          processId: wfParams.processId,
          summaryId: data.summaryId,
          caseId: wfParams.caseId,
          appName: wfParams.appEnumStr,
          isTemplate: wfParams.isTemplate,
          defaultNodeName: wfParams.defaultNodeName,
          defaultNodeLable: wfParams.defaultNodeLable,
          nps: wfParams.nps,
          appEnumStr: wfParams.appEnumStr,
          flowPermAccountId: wfParams.flowPermAccountId,
          bodyType: wfParams.bodyType
        };
      } else {
        params = { ...data };
        let isForm = false;
        let isCollaboration =
          params.appEnumStr == 'collaboration' || params.appName == 'collaboration';
        if (managerType == 'mySupervise' && dataType == 'all') {
          isForm = params.formAppId && params.bodyType == '20';
        } else {
          isForm = params.formAppId && params.templeteId;
        }

        if (isCollaboration && isForm) {
          params.spk = 'collaboration_template_form';
          params.nps = 'form';
        }
      }

      editFlowChartFn(params, row, buttonParams, { managerType, dataType });
    },
    editFlowChartFn: editFlowChartFn,
    // 流程终止
    stopFlowChart(row, callback, { managerType, dataType } = {}) {
      var data = row;
      var params = {};
      if (dataType === 'workflowBug') {
        // 流程异常
        stopWorkflow(row, callback, null, null, { managerType, dataType });
      } else {
        params = { ...data };
        stopWorkflowFn(params, null, callback);
      }
    },
    // 流程终止
    repealflowChart(row, callback, { managerType, dataType } = {}) {
      var data = row;
      var params = {};
      if (dataType === 'workflowBug') {
        // 流程异常
        repealWorkflow(row, callback, null, null, { managerType, dataType });
      } else {
        params = { ...data };
        repealWorkflowFn(params, null, callback);
      }
    },
    // 标记为已处理
    dealflowChart(row, callback) {
      var data = row;
      dealProblem(null, data, callback);
    },
    // 打印
    popprint(content) {
      var printContentBody = '';
      var cssList = new ArrayList();
      var pl = new ArrayList();
      var contentBody = content;
      var contentBodyFrag = '';
      const pageCssList = [...document.getElementsByTagName('link')];

      pageCssList.forEach((css) => {
        cssList.add(css.href);
      });

      contentBodyFrag = new PrintFragment(printContentBody, contentBody);
      pl.add(contentBodyFrag);
      printList(pl, cssList);
    },
    // 导出
    exportExcel(params, total, { managerType, dataType }) {
      var exportExcelProce = $.progressBar();
      var o = params || {};
      var url = _ctxPath + '/workflowmanage/workflowmanage.do?method=workflowDataToExcel';
      if (dataType === 'workflowBug') {
        url =
          _ctxPath +
          '/workflow/designer.do?method=workflowProblemToExcel' +
          CsrfGuard.getUrlSurffix();
      }

      $.batchExport(total, (page, size) => {
        o['page'] = page;
        o['size'] = size;
        o['fileName'] = dataType !== 'workflowBug' ? 'workflowData_' : 'workflowProblem_' + page; //文件名
        exportExcelProce.close();
        $.fn.jsonSubmit({
          action: url,
          paramObj: o,
          callback: function () { }
        });
      });
    },
    // 标题点击跳转
    titleClick(rowData, { managerType, dataType } = {}) {
      let _dataType = dataType;
      const _this = this;
      if (dataType === 'workflowBug') {
        let affairId = rowData.affairId;
        if (!affairId || affairId == 'null') {
          $.alert($.i18n('workflow.supervise.bugreport.canot.operation.js'));
          return;
        }
        let affairObj = getAffair(affairId);
        let _appName = 'collaboration';
        if (affairObj.app == 4) {
          _appName = 'edoc';
        }
        let SPK = affairObj.spk;
        let NPS = affairObj.nps;
        if (!SPK || SPK == 'undefined') {
          SPK = 'freeFlow';
        }
        if (!NPS || NPS == 'undefined') {
          NPS = 'default';
        }
        let options = {
          targetWin: window.getCtpTop(),
          caseId: affairObj.summaryState === 2 ? '' : affairObj.caseId,
          processId: affairObj.processId,
          isTemplate: false,
          showHastenButton: false,
          appName: _appName,
          currentNodeId: affairObj.summaryState === 2 ? '' : affairObj.activityId,
          scene: 3,
          SPK: SPK,
          NPS: NPS
        };

        if (this.isAdmin) {
          showDiagram(options);
        } else {
          let _superviseManager = new superviseManager();
          let isInProcess = _superviseManager.isMemberInProcess(affairObj.objectId);
          if (isInProcess) {
            let url =
              window._ctxPath +
              '/collaboration/collaboration.do?method=summary&summaryId=' +
              affairObj.objectId;
            collaborationApi.showSummayDialogByURL(url);
          } else {
            showDiagram(options);
          }
        }
      } else {
        let data = rowData;
        //开启密级时候只能看流程图
        secretLevelEnable = getSecretLevelEnable();

        if (secretLevelEnable && secretLevelEnable == true) {
          _this.showFlowChart(data);
          return;
        }

        if (managerType == 'mySupervise') {
          var url = '';
          var _superviseManager = new superviseManager();

          var obj = new Object();
          obj.objId = data.summaryId;
          obj.openFrom = 'supervise';

          var reBack = _superviseManager.checkSuperviseIsCancel(obj);

          if (reBack) {
            $.alert(reBack);
            return;
          }

          var detailPageUrl = data.detailPageUrl;

          if (!detailPageUrl) {
            detailPageUrl = 'collaboration/collaboration.do?method=summary';
          }

          var _affairId = null;

          if (_dataType == 'all') {
            _affairId = getSenderAffairId(data.summaryId);
          } else {
            _affairId = data.id;
          }

          url =
            _ctxPath +
            '/' +
            detailPageUrl +
            '&affairId=' +
            _affairId +
            '&summaryId=' +
            data.summaryId +
            '&openFrom=supervise&type=' +
            data.status;
          collaborationApi.showSummayDialogByURL(url);
        } else if (window._currentUser.isAdmin) {
          if (data.quickSend && data.quickSend == true) {
            return;
          }

          _this.showFlowChart(data);
        } else {
          var _superviseManager = new superviseManager();

          var isInProcess = _superviseManager.isMemberInProcess(data.summaryId);

          if (isInProcess) {
            var url =
              _ctxPath +
              '/collaboration/collaboration.do?method=summary&summaryId=' +
              data.summaryId;
            collaborationApi.showSummayDialogByURL(url);
          } else {
            _this.showFlowChart(data);
          }
        }
      }
    },
    // 流程日志
    showDetailLogDialog(summaryId, processId, showFlag, affairId) {
      let dialog = $.dialog({
        url:
          window._ctxPath +
          '/detaillog/detaillog.do?method=showDetailLog&summaryId=' +
          summaryId +
          '&processId=' +
          processId +
          '&showFlag=' +
          showFlag,
        width: 1040,
        height: 590,
        title: $.i18n('collaboration.sendGrid.findAllLog'), //查看明细日志
        targetWindow: window.getCtpTop()
      });
    },
    // 获取标题icon
    getTitleIcon(type, val) {
      const stateMap = {
        1: 'xicon-process-terminate',
        3: 'xicon-process-end'
      };
      const iconMap = {
        // 重要程度
        importantLevel: 'xicon-important' + (val - 1),
        // 流程状态
        state: stateMap[val],
        // 附件
        hasAttachment: 'xicon-affix',
        // 10 HTML正文，90 第三方正文
        bodyType: this.convertPortalBodyType(val),
      };

      return iconMap[type] && iconMap[type];
    },
    convertPortalBodyType(bodyType) {
      let bodyTypeClass = 'html_16';
      if ('FORM' === bodyType || '20' === bodyType) {
        bodyTypeClass = 'green-color xicon-form-text';
      } else if ('TEXT' === bodyType || '30' === bodyType) {
        bodyTypeClass = 'txt_16';
      } else if ('OfficeWord' === bodyType || '41' === bodyType) {
        bodyTypeClass = 'office-word-icon xicon-word';
      } else if ('OfficeExcel' === bodyType || '42' === bodyType) {
        bodyTypeClass = 'office-excel-icon xicon-excel';
      } else if ('WpsWord' === bodyType || '43' === bodyType) {
        bodyTypeClass = 'wps-color xicon-wps';
      } else if ('WpsExcel' === bodyType || '44' === bodyType) {
        bodyTypeClass = 'wps-color xicon-excel';
      } else if ('Pdf' === bodyType || '45' === bodyType) {
        bodyTypeClass = 'pfd-color xicon-pdf';
      } else if ('Ofd' === bodyType || '46' === bodyType) {
        bodyTypeClass = 'ofd-color xicon-ofd';
      } else if ('videoConf' === bodyType) {
        bodyTypeClass = 'attachment-color xicon-meeting-video';
      }
      bodyTypeClass += ' icon-font';
      return bodyTypeClass;
    },
    // 查看流程图
    showFlowChart(rowData = {}) {
      let { appName, caseId, processId, templeteId, activityId, appEnumStr, spk, nps, bodyType } =
        rowData;

      if (!spk || spk == 'undefined') {
        spk = 'freeFlow';
      }

      if (!nps || nps == 'undefined') {
        nps = 'default';
      }

      var isTemplate = templeteId && templeteId != 'null';
      var options = {
        targetWin: getCtpTop(),
        caseId: caseId,
        processId: processId,
        isTemplate: isTemplate,
        showHastenButton: false,
        appName: appName,
        currentNodeId: activityId,
        scene: 3,
        SPK: spk,
        NPS: nps,
        canExePrediction:
          (bodyType === '20' || nps === 'form') && window._hasPlugin('workflowAdvanced')
      };
      showDiagram(options);
    },
    // 督办摘要
    superviseContent(rowData, _callback) {
      let { summaryId, status } = rowData;
      let superviseId = rowData.superviseDetailId || rowData.id;
      var url =
        _ctxPath +
        '/supervise/supervise.do?method=showDescription&summaryId=' +
        summaryId +
        '&superviseId=' +
        superviseId;
      var but = new Array();
      var dialogs = ''; //当是未办结状态时，才显示确定按钮

      if (status == 0) {
        but.push({
          text: $.i18n('common.button.ok.label'),
          handler: function handler() {
            var returnValue = dialogs.getReturnValue();

            if (returnValue != null) {
              var map = $.parseJSON(returnValue);
              var content = map.content;
              var url =
                _ctxPath +
                '/supervise/supervise.do?method=updateContent&content=' +
                content +
                '&superviseId=' +
                map.superviseId;
              $.fn.jsonSubmit({
                action: url,
                callback: function callback() {
                  setTimeout(function () {
                    dialogs.close();
                    _callback && _callback();
                  }, 10);
                }
              });
            }
          }
        });
        but.push({
          text: $.i18n('common.button.cancel.label'),
          handler: function handler() {
            dialogs.close();
          }
        });
      } else {
        but.push({
          text: $.i18n('common.button.close.label'),
          handler: function handler() {
            dialogs.close();
          }
        });
      } //督办摘要 弹出dialog

      dialogs = $.dialog({
        url: url,
        width: 500,
        height: 350,
        targetWindow: getCtpTop(),
        title: $.i18n('supervise.col.label'),
        buttons: but
      });
    },

    // 督办期限
    changeAwake(ev, rowData, templeteIds, _callback) {
      var awakeId = rowData.id;

      if (rowData.superviseDetailId) {
        awakeId = rowData.superviseDetailId;
      }

      var time = getCurrentTime();
      const evRect = ev.target.getBoundingClientRect();
      const bodyRect = document.body.getBoundingClientRect();

      const left = evRect.left - 130;
      let top = evRect.top;
      if (bodyRect.height - evRect.top > 380) {
        top = evRect.top + 30;
      } else {
        top = evRect.top - 340;
      }
      $.calendar({
        displayArea: 'awakeDate_' + awakeId,
        position: [left, top],
        returnValue: true,
        ifFormat: '%Y-%m-%d %H:%M',
        daFormat: '%Y-%m-%d %H:%M',
        dateString: time,
        singleClick: true,
        showsTime: true,
        onUpdate: (_date) => {
          var date1 = getCurrentDate();
          var date1s = date1.split('-');
          var bdate = new Date(date1s[0], date1s[1] - 1, date1s[2]);
          var date2 = _date.substring(0, 10);
          var date2s = date2.split('-');
          var edate = new Date(date2s[0], date2s[1] - 1, date2s[2]);
          var url =
            _ctxPath +
            '/supervise/supervise.do?method=modifySupervise&superviseId=' +
            awakeId +
            '&awakeDate=' +
            _date +
            '&app=1';
          url = addUrlPath(url, templeteIds);

          if (bdate.getTime() > edate.getTime()) {
            var confirm = $.confirm({
              msg: $.i18n('collaboration.common.supervise.thisTimeXYouset'),
              //您设置的督办日期小于当前日期,是否继续?
              ok_fn: function ok_fn() {
                $.fn.jsonSubmit({
                  action: url,
                  callback: function callback() {
                    _callback && _callback();
                  }
                });
              },
              cancel_fn: function cancel_fn() {
                confirm.close();
              }
            });
          } else {
            $.fn.jsonSubmit({
              action: url,
              callback: function callback() {
                _callback && _callback();
              }
            });
          }
        },
        autoShow: true,
        isClear: true
      });
    },

    // 批量修改流程
    batchEditFlowChart(selectRows, _callback, { managerType, dataType } = {}) {
      callBackendMethod('superviseManager', 'canBatchModifyData', {
        success: function success(result) {
          if ('true' == result.currentOperation) {
            $.alert($.i18n('workflow.manager.supervise.modify.msg3.js'));
          } else {
            if (checkSameTemplate(selectRows)) {
              var selectRow = JSON.parse(JSON.stringify(selectRows[0])); //克隆对象

              var processIdAndCaseIdAndFormAppIdAndMasterId = '';

              for (var i = 0; i < selectRows.length; i++) {
                if (processIdAndCaseIdAndFormAppIdAndMasterId == '') {
                  processIdAndCaseIdAndFormAppIdAndMasterId =
                    selectRows[i].processId +
                    '_' +
                    selectRows[i].caseId +
                    '_' +
                    selectRows[i].formAppId +
                    '_' +
                    selectRows[i].formRecordId;
                } else {
                  processIdAndCaseIdAndFormAppIdAndMasterId +=
                    ',' +
                    selectRows[i].processId +
                    '_' +
                    selectRows[i].caseId +
                    '_' +
                    selectRows[i].formAppId +
                    '_' +
                    selectRows[i].formRecordId;
                }
              }

              var isCollaboration =
                selectRow.appEnumStr == 'collaboration' || selectRow.appName == 'collaboration';
              var isForm = false;

              if (managerType == 'mySupervise' && dataType == 'all') {
                isForm = selectRow.formAppId && selectRow.bodyType == '20';
              } else {
                isForm = selectRow.formAppId && selectRow.templeteId;
              }

              if (isCollaboration && isForm) {
                selectRow.spk = 'collaboration_template_form';
                selectRow.nps = 'form';
              }

              var tmanager = new templateManager();
              tmanager.getCtpTemplate(selectRow.templeteId, {
                success: function success(obj) {
                  if (obj == null || obj == '') {
                    $.alert(obj);
                  } else if (!obj.workflowId && obj.type == 'text') {
                    $.alert($.i18n('workflow.manager.supervise.modify.mag0.js')); //"格式模板不能批量修改流程"
                  } else {
                    selectRow.formAppId = obj.formAppId;
                    selectRow.flowPermAccountId = obj.flowPermAccountId || obj.orgAccountId;
                    selectRow.caseId = '-1';
                    batchEditFlowChartFn(
                      selectRow,
                      processIdAndCaseIdAndFormAppIdAndMasterId,
                      obj,
                      null,
                      _callback
                    );
                  }
                }
              });
            }
          }
        }
      });
    },
    // 批量修改所有流程
    batchEditAllFlowChart(
      allData,
      _callback,
      { managerType, dataType, searchParams, urlParams } = {}
    ) {
      callBackendMethod('superviseManager', 'canBatchModifyData', {
        success: function success(result) {
          if ('true' == result.currentOperation) {
            $.alert($.i18n('workflow.manager.supervise.modify.msg3.js'));
          } else {
            var teamplateId = searchParams?.operationTypeIds;
            if (!teamplateId) {
              $.alert($.i18n('workflow.manager.supervise.modify.mag14.js')); //请选择一个模板
              return;
            }

            if (teamplateId.indexOf(',') > 0) {
              $.alert($.i18n('workflow.manager.supervise.modify.mag2.js')); //批量操作只能修改同一模板的数据！
              return;
            }
            /**
             *
             * 1.查询数据total
             * 2.小于200条数据同步处理，大于200条异步处理
             * 3.打开流程图
             * 4.修改流程后确定（异步分页获取数据并修改对应流程）
             * 5.完了以后发送消息
             *
             */

            var tmanager = new templateManager();
            tmanager.getCtpTemplate(teamplateId, {
              success: function success(obj) {
                if (obj == null || obj == '') {
                  $.alert(obj);
                } else {
                  var o = { ...searchParams };
                  let { srcFrom, templeteIds } = urlParams;
                  if (srcFrom == 'bizconfig' && templeteIds != null) {
                    o.operationType = 'template';
                    o.operationTypeIds = templeteIds;
                  } else if (managerType !== 'mySupervise') {
                    o.operationType = 'template';
                  }

                  o.managerType = managerType;
                  if (dataType == 'done') {
                    o.status = '1';
                  } else if (dataType == 'pending') {
                    o.status = '0';
                  }

                  o.onlyFindCount = 'true';
                  var re;

                  if (managerType == 'mySupervise') {
                    o.managerType = 'mySupervise';

                    var _superviseManager = new superviseManager();

                    re = _superviseManager.getAllSuperviseList4Col({}, JSON.stringify(o));

                    if (re && re.total == 0) {
                      $.alert($.i18n('workflow.manager.supervise.modify.mag13.js'));
                      return;
                    }

                    if (re && re.total) {
                      __batchEdit(
                        obj,
                        re.total,
                        true,
                        { managerType, dataType, allData, searchParams },
                        _callback
                      );
                    }
                  } else {
                    var wmManager = new workflowManageManager();
                    re = wmManager.getSuperviseAllTemplateData(JSON.stringify(o));

                    if (re && re[0] == '0') {
                      $.alert($.i18n('workflow.manager.supervise.modify.mag13.js'));
                      return;
                    }

                    if (re && re[0]) {
                      __batchEdit(
                        obj,
                        parseInt(re[0]),
                        true,
                        { managerType, dataType, allData, searchParams },
                        _callback
                      );
                    }
                  }
                }
              }
            });
          }
        }
      });
    },

    initProcessShowType() {
      if (this.showType == 0) {
        return;
      }
      const defaultValues = getDefaultValueSearchCondition(this.searchConditions);
      let sendParams = [
        {
          ...this.cachParams,
          ...defaultValues,
          showType: this.showType + ''
        }
      ];
      let url = `${window._ctxPath}/ajax.do?method=ajaxAction&managerName=superviseManager`;
      const managerMethod = 'getProcessMsgByTemplates';
      const args = `managerMethod=${managerMethod}&arguments=${formatRequestDataToJSON(
        sendParams
      )}`;

      window.axios
        .post(url, args, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
          }
        })
        .then((data) => {
          const result = data.data;
          if (result) {
            this.specialSearchConditionList = result.map((item, index) => {
              const newItem = {
                id: index,
                values: []
              };
              for (let key in item) {
                if (key == 'templateName' || key == 'templateId') {
                  newItem[key] = item[key];
                } else {
                  newItem.values.push({
                    id: key,
                    name: item[key]
                  });
                }
              }

              return newItem;
            });
          }
        });
    },
    // 数据呈现颗粒度条件值改变
    onSpecialSearchConditionClicked(value) {
      const params = {};
      params.clickedItemId = value.id;
      if (value.templateId) {
        params.operationTypeIds = value.templateId;
        params.operationType = 'template';
      }

      if (this.showType == '1') {
        //按节点
        params.activityId = parseInt(value.id);
      } else if (this.showType == '2') {
        //按泳道
        params.swimlaneId = parseInt(value.id);
      }

      this.specialSearchSelectedValue = value.templateId + '-' + value.id;
      this.specialSearchConditionParams = params;
      this.pagination.page = 1;
      this.initTableData(params);
    }
  }
};
